﻿using Autofac;
using Microsoft.Extensions.Configuration;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SD.App.Desktop
{
    public class SqlSugarModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // 1. 注册 SqlSugarConfig：通过 IConfiguration 动态获取连接串
            builder.Register(c =>
            {
                // 注入连接配置服务（支持运行时修改）
                var configuration = c.Resolve<IConfiguration>();
                var logger = c.Resolve<ILogger>();

                // 动态构建连接串（从配置服务获取实时参数）
                string connectionString = configuration["SqlSugar:PostgreSQLConnection"] ?? "";
                string dbType = configuration["SqlSugar:DbType"] ?? "";
                bool enableLog = bool.Parse(configuration["SqlSugar:EnableLog"] ?? "true");

                logger.Information("SqlSugar 配置初始化：数据库类型={DbType}，连接串={ConnectionString}", dbType, connectionString);

                return new SqlSugarConfig
                {
                    DbType = dbType,
                    ConnectionString = connectionString,
                    EnableLog = enableLog
                };
            })
            .AsSelf()
            .InstancePerLifetimeScope(); // 作用域生命周期：每次作用域重新获取配置

            // 2. 注册 SqlSugarContext（作用域生命周期：与配置同步更新）
            builder.RegisterType<SqlSugarContext>()
                   .AsSelf()
                   .InstancePerLifetimeScope();
        }
    }
}
